package com.leo.common.core.config;

import com.leo.common.core.util.MessageUtils;
import feign.form.util.CharsetUtil;
import org.springframework.boot.autoconfigure.context.MessageSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.util.StringUtils;

import java.time.Duration;

/**
 * <p>
 * 国际化配置
 * </p>
 *
 * @author ：Leo
 * @since ：2021-03-01 11:23
 */
@Configuration
public class MessageSourceConfig {

	@Bean
	@ConfigurationProperties(prefix = "spring.messages")
	public MessageSourceProperties messageSourceProperties() {
		return new MessageSourceProperties();
	}

	@Bean
	public MessageSource messageSource(MessageSourceProperties properties) {
		ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
		messageSource.setBasename("classpath:i18n/messages");
		if (StringUtils.hasText(properties.getBasename())) {
			messageSource.addBasenames(StringUtils
					.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
		}

		if (properties.getEncoding() == null) {
			messageSource.setDefaultEncoding(CharsetUtil.UTF_8.name());
		}
		else {
			messageSource.setDefaultEncoding(properties.getEncoding().name());
		}
		messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
		Duration cacheDuration = properties.getCacheDuration();
		if (cacheDuration != null) {
			messageSource.setCacheMillis(cacheDuration.toMillis());
		}
		messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
		messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
		return messageSource;
	}

	/**
	 * 注入国际化工具类
	 * @param messageSource messageSource
	 * @return MessageUtils
	 */
	@Bean
	public MessageUtils messageUtils(MessageSource messageSource) {
		return new MessageUtils(messageSource);
	}

}
